package com.morningstar.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.common.result.ServiceCheckResult;
import com.morningstar.system.dao.entity.SysMenu;
import com.morningstar.system.dao.mapper.SysMenuMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author yanglianshan
 * @since 2023-06-28
 */
@Slf4j
@Service
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {

    @Resource
    private SysMenuMapper menuMapper;
    
    public ServiceCheckResult checkAddAndUpdate(SysMenu sysMenu) {
        LambdaQueryWrapper<SysMenu> checkMenuNameWrapper = new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getMenuName, sysMenu.getMenuName())
                .ne(sysMenu.getMenuId() != null, SysMenu::getMenuId, sysMenu.getMenuId());
        if (this.count(checkMenuNameWrapper) > 0) {
            return new ServiceCheckResult(true, "菜单名称已存在");
        }
        return new ServiceCheckResult(false);
    }

    /**
     * 获取用户权限
     *
     * @param userId 用户Id
     * @return 用户菜单
     */
    public List<String> selectMenuPerms(Long userId) {
        return this.selectUserMenus(userId)
                .stream()
                .map(SysMenu::getPerms)
                .filter(StringUtils::isNotBlank)
                .toList();
    }

    /**
     * 查询用户权限菜单
     *
     * @param userId 用户Id
     * @return 用户菜单
     */
    public List<SysMenu> selectUserMenus(Long userId) {
        return menuMapper.selectUserMenus(userId);
    }

}
